package com.monitor.util;

import oshi.SystemInfo;
import oshi.hardware.*;
import oshi.software.os.OperatingSystem;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;

/**
 * 系统信息工具类
 * 用于获取系统硬件和软件信息
 */
public class SystemInfoUtil {
    
    private static final SystemInfo systemInfo = new SystemInfo();
    private static final HardwareAbstractionLayer hardware = systemInfo.getHardware();
    private static final OperatingSystem os = systemInfo.getOperatingSystem();
    
    /**
     * 获取系统信息
     * @return 包含系统信息的Map
     */
    public static Map<String, String> getSystemInfo() {
        Map<String, String> info = new HashMap<>();
        
        try {
            // 操作系统信息
            info.put("osName", os.getFamily());
            info.put("osVersion", os.getVersionInfo().getVersion());
            info.put("osArch", System.getProperty("os.arch"));
            
            // 计算机信息
            ComputerSystem computerSystem = hardware.getComputerSystem();
            info.put("manufacturer", computerSystem.getManufacturer());
            info.put("model", computerSystem.getModel());
            info.put("serialNumber", computerSystem.getSerialNumber());
            
            // 内存信息
            GlobalMemory memory = hardware.getMemory();
            long totalMemory = memory.getTotal();
            info.put("totalMemory", formatBytes(totalMemory));
            info.put("totalMemoryGB", String.valueOf(totalMemory / (1024 * 1024 * 1024)));
            
            // 硬盘信息
            List<HWDiskStore> diskStores = hardware.getDiskStores();
            StringBuilder diskInfo = new StringBuilder();
            long totalDiskSize = 0;
            for (HWDiskStore disk : diskStores) {
                if (diskInfo.length() > 0) {
                    diskInfo.append("; ");
                }
                diskInfo.append(disk.getModel()).append(" (").append(formatBytes(disk.getSize())).append(")");
                totalDiskSize += disk.getSize();
            }
            info.put("diskInfo", diskInfo.toString());
            info.put("totalDiskSizeGB", String.valueOf(totalDiskSize / (1024 * 1024 * 1024)));
            
            // 网卡信息
            List<NetworkIF> networkIFs = hardware.getNetworkIFs();
            StringBuilder networkInfo = new StringBuilder();
            String macAddress = "";
            for (NetworkIF net : networkIFs) {
                if (net.getBytesRecv() > 0 || net.getBytesSent() > 0) {
                    if (networkInfo.length() > 0) {
                        networkInfo.append("; ");
                    }
                    networkInfo.append(net.getDisplayName());
                    if (macAddress.isEmpty() && !net.getMacaddr().equals("00:00:00:00:00:00")) {
                        macAddress = net.getMacaddr();
                    }
                }
            }
            info.put("networkInfo", networkInfo.toString());
            info.put("macAddress", macAddress);
            
            // 显卡信息
            List<GraphicsCard> graphicsCards = hardware.getGraphicsCards();
            StringBuilder gpuInfo = new StringBuilder();
            for (GraphicsCard gpu : graphicsCards) {
                if (gpuInfo.length() > 0) {
                    gpuInfo.append("; ");
                }
                gpuInfo.append(gpu.getName());
                if (gpu.getVRam() > 0) {
                    gpuInfo.append(" (").append(formatBytes(gpu.getVRam())).append(")");
                }
            }
            info.put("gpuInfo", gpuInfo.toString());
            
            // 处理器信息
            CentralProcessor processor = hardware.getProcessor();
            info.put("cpuName", processor.getProcessorIdentifier().getName());
            info.put("cpuCores", String.valueOf(processor.getLogicalProcessorCount()));
            
        } catch (Exception e) {
            e.printStackTrace();
            info.put("error", "获取系统信息时发生错误: " + e.getMessage());
        }
        
        return info;
    }
    
    /**
     * 获取MAC地址（备用方法）
     * @return MAC地址
     */
    public static String getMacAddress() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (!networkInterface.isLoopback() && networkInterface.isUp()) {
                    byte[] mac = networkInterface.getHardwareAddress();
                    if (mac != null && mac.length == 6) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < mac.length; i++) {
                            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
                        }
                        return sb.toString();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }
    
    /**
     * 格式化字节数
     * @param bytes 字节数
     * @return 格式化后的字符串
     */
    private static String formatBytes(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        }
        int exp = (int) (Math.log(bytes) / Math.log(1024));
        String pre = "KMGTPE".charAt(exp - 1) + "";
        return String.format("%.1f %sB", bytes / Math.pow(1024, exp), pre);
    }
    
    /**
     * 获取硬件ID（基于多个硬件特征生成）
     * @return 硬件ID
     */
    public static String getHardwareId() {
        try {
            Map<String, String> info = getSystemInfo();
            String combined = info.get("manufacturer") + "|" + 
                            info.get("model") + "|" + 
                            info.get("serialNumber") + "|" + 
                            info.get("macAddress");
            
            // 生成简单的哈希值作为硬件ID
            return String.valueOf(Math.abs(combined.hashCode()));
        } catch (Exception e) {
            return "UNKNOWN";
        }
    }
}